<template>
  <div class="app-container">
    <div style="margin-bottom: 10px">
      <span>人员爬虫配置</span>
    </div>
    <el-form
      ref="formData"
      size="small"
      :model="formData"
      :inline="true"
      class="demo-form-inline"
      style="margin-left: 20px;"
    >
      <el-row>
        <el-col :span="6">
          <el-form-item label="爬虫名称:" prop="spiderName">
            <el-input
              v-model="formData.spiderName"
              placeholder="请输入爬虫名称"
              clearable
              @change="fetchData"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="负责人:" prop="manager">
            <el-select
              v-model="formData.manager"
              clearable
              placeholder="请选择负责人"
              @change="fetchData"
            >
              <el-option
                v-for="item in managerList"
                :key="item.manager"
                :label="item.manager"
                :value="item.manager"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10" style=" margin-bottom: 8px;">
        <el-col :span="1.5">
          <el-button ref="fetchData" icon="el-icon-search" type="primary" size="mini" @click="fetchData">查询</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button ref="resetData" icon="el-icon-refresh" type="primary" size="mini" @click="resetData">重置</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button ref="addData" icon="el-icon-circle-plus-outline" type="primary" size="mini" @click="addData">新增</el-button>
        </el-col>
      </el-row>
    </el-form>

    <el-table
      ref="tableList"
      v-loading="loading"
      :data="list"
      :header-cell-style="headStyle"
      :cell-style="cellStyle"
    >
      <el-table-column label="序号" width="50">
        <template slot-scope="scope">
          {{ (page - 1) * limit + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="spiderName" label="爬虫名称" align="center" />
      <el-table-column prop="manager" label="负责人" align="center" />
      <el-table-column prop="taskName" label="任务名称" align="center" />
      <el-table-column prop="taskClass" label="任务类名" align="center" />
      <el-table-column prop="queueName" label="队列名称" align="center" />
      <el-table-column prop="scheduledName" label="定时任务" align="center" />

      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="editById(scope.row.id)"
          >
            修改
          </el-button>
          <el-button
            type="danger"
            size="mini"
            icon="el-icon-delete"
            @click="foreverRemove(scope.row.id, scope.row.showId)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      title="修改配置信息"
      :visible.sync="dialogTableVisible"
      width="1000px"
      @close="closeDetailVisable('detailObj')"
    >
      <el-form
        ref="detailObj"
        v-loading="dialogLoading"
        :model="detailObj"
        label-width="100px"
        class="demo-form-inline"
        :rules="rules"
      >
        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item label="爬虫名称" prop="spiderName">
              <el-input v-model="detailObj.spiderName" clearable size="small" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="负责人" prop="manager">
              <el-input v-model="detailObj.manager" clearable size="small" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="任务名称" prop="taskName">
              <el-input v-model="detailObj.taskName" clearable size="small" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="任务类名" prop="taskClass">
              <el-input v-model="detailObj.taskClass" clearable size="small" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="队列名称" prop="queueName">
              <el-input v-model="detailObj.queueName" clearable size="small" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="定时任务id" prop="scheduledId">
              <el-input v-model="detailObj.scheduledId" :disabled="true" clearable size="small" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="定时任务" prop="scheduledName">
              <el-input v-model="detailObj.scheduledName" :disabled="scheduledDisabled" size="small" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-button v-if="dialogLoading" type="warning" size="mini" disabled style="margin-left: 1px; height: 30px; margin-top: 4px">加载中...</el-button>
            <el-button
              v-else-if="scheduledButton"
              type="danger"
              size="mini"
              style="margin-left: 1px; height: 30px; margin-top: 4px"
              @click="unupdateScheduledName"
            >
              解绑
            </el-button>
            <el-button
              v-else
              type="success"
              size="mini"
              style="margin-left: 1px; height: 30px; margin-top: 4px"
              @click="updateScheduledName"
            >
              绑定
            </el-button>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogTableVisible = false; detailObj = {}">
          取消
        </el-button>
        <el-button type="primary" size="small" @click="detailSubmit">
          确定
        </el-button>
      </div>
    </el-dialog>

    <!-- 分页组件 -->
    <el-pagination
      background
      :current-page="page"
      :total="total"
      :page-size="limit"
      :page-sizes="[10, 20, 50, 100]"
      prev-text="上一页"
      next-text="下一页"
      style="padding: 30px 0; text-align: center"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="changePageSize"
      @current-change="changeCurrentPage"
    />
  </div>
</template>
<script>
import variables from '@/styles/variables.scss'
import personApi from '@/api/person/person'

export default {
  name: 'PersonConfig',
  data() {
    return {
      total: 0, // 数据库总记录数
      page: 1, // 默认页码
      limit: 10, // 每页记录数
      formData: { // 表单数据
        spiderName: '',
        manager: ''
      },
      detailObj: {
        id: 0,
        spiderName: '',
        manager: '',
        taskName: '',
        taskClass: '',
        queueName: '',
        scheduledId: 0,
        scheduledName: ''
      },
      list: [], // 列表数据
      managerList: [], // 来源列表
      loading: false,
      dialogLoading: false,
      rules: {
        spiderName: [{ required: true, message: '请输入爬虫名称', trigger: 'blur' }],
        manager: [{ required: true, message: '请输入负责人', trigger: 'blur' }],
        taskName: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
        taskClass: [{ required: true, message: '请输入任务类名', trigger: 'blur' }],
        queueName: [{ required: true, message: '请输入队列名称', trigger: 'blur' }]
      },
      dialogTableVisible: false,
      scheduledButton: true, // 绑定按钮
      scheduledDisabled: true // 定时任务名称输入框
    }
  },

  created() {
    this.fetchData()
    this.fetchList()
  },

  methods: {
    fetchData() {
      this.loading = true
      personApi.configListPage(this.page, this.limit, this.formData).then((response) => {
        this.list = response.data.result.list
        this.total = response.data.result.total
        this.loading = false
      })
      this.fetchList()
      this.$nextTick(() => {
        this.$refs.fetchData.$el.blur()
      })
    },

    fetchList() {
      personApi.getConfigManagerList().then((response) => {
        this.managerList = response.data.result
      })
    },

    fetchDataById(id) {
      this.dialogLoading = true
      personApi.getConfigById(id).then((response) => {
        this.dialogLoading = false
        this.detailObj = response.data.result
        // 根据定时任务是否存在显示置灰
        if (this.detailObj.scheduledName === '') {
          this.scheduledDisabled = false
          this.scheduledButton = false
        } else {
          this.scheduledDisabled = true
          this.scheduledButton = true
        }
      })
    },

    // 绑定定时任务
    updateScheduledName() {
      if (!this.detailObj.scheduledName) {
        this.$message.warning('任务名称为空')
      } else {
        personApi.updateScheduledName(this.detailObj.scheduledName).then((response) => {
          if (response.code === 200) {
            this.$message({
              message: '绑定成功',
              type: 'success'
            })
            this.detailObj.scheduledId = response.data.scheduledId
            this.scheduledButton = true // 定时任务绑定解绑按钮的显示
            this.scheduledDisabled = true
          }
        })
      }
    },

    // 解绑定时任务
    unupdateScheduledName() {
      this.$confirm('是否解绑?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.detailObj.scheduledId = 0
        this.detailObj.scheduledName = ''
        this.scheduledButton = false
        this.scheduledDisabled = false
      })
    },

    resetData() {
      this.formData = {
        spiderName: '',
        manager: ''
      }
      this.page = 1
      this.limit = 10
      this.fetchData()
    },

    // 修改配置信息对话框
    editById(id) {
      // 根据id查询数据
      this.fetchDataById(id)

      // 打开对话框
      this.dialogTableVisible = true
    },

    addData() {
      this.detailObj = {
        id: 0,
        spiderName: '',
        manager: '',
        taskName: '',
        taskClass: '',
        queueName: '',
        scheduledId: 0,
        scheduledName: ''
      }
      this.scheduledDisabled = false
      this.scheduledButton = false

      this.dialogTableVisible = true
    },

    // 修改配置信息
    detailSubmit() {
      this.$refs.detailObj.validate((err) => {
        // true表示校验通过，false表示校验失败，validate方法是整个表单所有字段都校验
        if (!err) {
          this.$message({
            message: '内容校验不通过',
            type: 'error'
          })
        } else {
          if (this.scheduledDisabled === false && this.detailObj.scheduledName !== '') {
            this.$message.warning('请输入正确的定时任务名称或置空')
          } else {
            this.$confirm('确定保存?', '提示', {
              cancelButtonText: '取消',
              confirmButtonText: '确定',
              type: 'warning'
            }).then(() => {
              if (this.detailObj.id === 0) {
                return personApi.addData(this.detailObj)
              } else {
                return personApi.updateById(this.detailObj)
              }
            }).then(() => {
              this.fetchData() // 刷新列表
              this.$message({
                type: 'success',
                message: '保存成功'
              })
              this.dialogTableVisible = false
            }).catch((reason) => {
              if (reason === 'cancel') {
                this.$message({
                  type: 'info',
                  message: '取消保存'
                })
              }
            })
          }
        }
      })
    },

    // 关闭修改弹窗
    closeDetailVisable(detailObj) {
      this[detailObj] = {
        id: 0,
        showId: 0,
        spiderName: '',
        manager: '',
        taskName: '',
        taskClass: '',
        queueName: '',
        scheduledId: 0,
        scheduledName: ''
      }
      this.$nextTick(() => {
        this.$refs[detailObj].clearValidate()
      })
    },

    // 根据id删除配置信息
    foreverRemove(id, showId) {
      this.$confirm('确定删除?', '提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning'
      }).then(() => {
        return personApi.foreverRemove(id, showId)
      }).then(() => {
        this.fetchData() // 刷新列表
        this.$message.success('删除成功')
      }).catch((reason) => {
        if (reason === 'cancel') {
          this.$message({
            type: 'info',
            message: '取消删除'
          })
        }
      })
    },

    // 每页展示条数的改变，size：回调函数, 表示当前选中的展示条数
    changePageSize(size) {
      this.limit = size
      this.fetchData()
    },

    // 翻页，page：回调函数, 表示当前选中的页码
    changeCurrentPage(page) {
      this.page = page
      this.fetchData()
    },

    // 表头style
    headStyle() {
      return 'color: black; backgroundColor: ' + variables.globalStyle
    },

    // 列style
    cellStyle({ row, column, rowIndex, columnIndex }) {
      return 'height: 50px'
    }
  }
}
</script>

<style scoped>

</style>
